<script setup>
import { ref } from 'vue'
import { Plus,Upload } from '@element-plus/icons-vue'
import { artAddChannelService } from '@/api/article'
import { useUserStore } from '@/stores/user'
const userStore = useUserStore()

const imageUrl = ref()
imageUrl.value = userStore.user.user_pic

const RefUpload = ref() // 用于按钮调出文件选择框
const submitImage = ref()
// 预览图片
const handleChange2 = (file) => {
  imageUrl.value = URL.createObjectURL(file.raw)
  submitImage.value = file.raw
}
// 上传图片到后端
const uploadImage2 = async () => {
  const formData = new FormData()
  formData.append('cover_img', submitImage.value)
  const { data } = await artAddChannelService(formData)
  console.log(data)
}
// 方法二
const handleChange = (uploadFile) => {
  // 基于 FileReader 读取图片做预览
  const reader = new FileReader()
  reader.readAsDataURL(uploadFile.raw)
  reader.onload = () => {
    imageUrl.value = reader.result
  }
}
const uploadImage = async () => {
  console.log(imageUrl.value)
  const { data } = await artAddChannelService(imageUrl.value)
  console.log(data)
}
</script>

<template>
    <el-card>
      <el-upload
      ref="RefUpload"
      class="avatar-uploader"
      :auto-upload="false"
      :show-file-list="false"
      :on-change="handleChange"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
    
    <el-button type="primary" style="margin-top: 20px;" :icon="Plus" 
    @click="RefUpload.$el.querySelector('input').click()" <--!--点击按钮调出文件选择框-->
    >选择图片</el-button>
   
    
    <el-button type="primary" style="margin-top: 20px;" :icon="Upload" @click='uploadImage'>上传头像</el-button>
  </el-card>

</template>
<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 278px;
      height: 278px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 278px;
      height: 278px;
      text-align: center;
    }
  }
}
</style>